<?php

namespace App\Http\Requests;

class ReviewOrderRequestOld extends BaseRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            "review" => [
                "required",
                "between:1,150"
            ],
            "order_items_ids" => [
                'required',
                'array',
                function ($attribute, $order_items_ids, $fail) {
                    $orderItems = $this->user()->orderItems;

                    // 获取未评价的数组
                    $NotEvaluated = [];

                    foreach ($order_items_ids as $orderItemsId) {
                        // 验证该用户是否有这些订单项
                        if (!$orderItem = $orderItems->where('id', $orderItemsId)->first()) {
                            return $fail('订单项id不存在');
                        }

                        if (!$orderItem->reviewed_at) {  // 如果已经评价了, 把id保存到数组里面
                            $NotEvaluated[] = $orderItemsId;
                        }
                    }

                    // 如果已经评价的数量等于订单项数量
                    if (count($order_items_ids) - count($NotEvaluated) == count($order_items_ids)) {
                        return $fail('该订单已经评价了');
                    }

                    // 修改$request->input()里的值
                    $this->offsetSet('order_items_ids', $NotEvaluated);
                }
            ]
        ];
    }
}
